﻿using FinScreen.Model;
using QuantBox.CSharp2CTPZQ;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FinScreen
{
    class MarketBase : Observable<CThostFtdcDepthMarketDataField>
    {
        private MdApiWrapper _md = new MdApiWrapper();

        public MarketBase()
        {
            _md.OnConnect += _md_OnConnect;
            _md.OnDisconnect += _md_OnDisconnect;
            _md.OnRspError += _md_OnRspError;
            _md.OnRtnDepthMarketData += _md_OnRtnDepthMarketData;
        }

        public void Load()
        {
            _md.Connect(@"D:\FinData\Market", "tcp://116.228.234.67:41213", "2011", "", "");
        }

        public void UnSubscribeInstruments(IEnumerable<string> instruments)
        {
            foreach (var instrument in instruments)
            {
                string id = instrument.Split('.')[0];
                string exchange = instrument.Split('.')[1].ToUpper();

                _md.Unsubscribe(id, "SSE");
            }
        }

        public void SubscribeInstruments(IEnumerable<string> instruments)
        {
            foreach (var instrument in instruments)
            {
                string id = instrument.Split('.')[0];
                string exchange = instrument.Split('.')[1].ToUpper();

                if(exchange == "SS")
                    _md.Subscribe(id, "SSE");
                else
                    _md.Subscribe(id, "SZSE");
            }
        }

        private void _md_OnRtnDepthMarketData(object sender, OnRtnDepthMarketDataArgs e)
        {
            OnNext(e.pDepthMarketData);
        }

        private void _md_OnRspError(object sender, OnRspErrorArgs e)
        {
        }

        private void _md_OnDisconnect(object sender, OnDisconnectArgs e)
        {
        }

        private void _md_OnConnect(object sender, OnConnectArgs e)
        {
        }
    }
}
